package com.gali.mall.controller;

import com.gali.mall.common.Const;
import com.gali.mall.common.ResultInfo;
import com.gali.mall.exception.GaLiException;
import com.gali.mall.exception.GaLiExceptionEnum;
import com.gali.mall.model.pojo.Product;
import com.gali.mall.request.productReq.*;
import com.gali.mall.service.ProductService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.UUID;

/**
 * @author gali
 * @date 2022/4/11 20:12
 */
@RestController
public class ProductController {
    @Autowired
    private ProductService productService;

    /**
     * 添加商品
     * @param addProductReq
     * @return
     */
    @PostMapping("/product/admin/add")
    public ResultInfo addProduct(@RequestBody @Valid AddProductReq addProductReq){
        Product product = new Product();
        BeanUtils.copyProperties(addProductReq,product);
        boolean flag = productService.addProduct(product);
        if (flag){
            return ResultInfo.success();
        }
        return ResultInfo.error(GaLiExceptionEnum.ADD_ERROR);
    }

    /**
     * 文件上传
     * @param file
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/product/upload")
    @ResponseBody
    public ResultInfo upload(@RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest){
        String fileName = file.getOriginalFilename();
        String suffix =fileName.substring(fileName.lastIndexOf("."));
        //获取uuid
        UUID uuid = UUID.randomUUID();
        //生成新的文件名
        String newFileName = uuid.toString()+suffix;
        System.out.println(Const.FILE_UPLOAD_DIR);
        File fileDirectory = new File(Const.FILE_UPLOAD_DIR);
        File destFile = new File(Const.FILE_UPLOAD_DIR+newFileName);
        if (!fileDirectory.exists()) {
            if (!fileDirectory.mkdir()) {
                throw new GaLiException(GaLiExceptionEnum.MKDIR_FALIED);
            }
        }
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return ResultInfo.success(getHost(new URI(httpServletRequest.getRequestURI()+""))+newFileName);
        } catch (URISyntaxException e) {
            return ResultInfo.error(GaLiExceptionEnum.UPLOAD_FALIED);
        }
    }
    private URI getHost(URI uri){
        URI effetiveURI;
        try {
            effetiveURI=new URI(uri.getScheme(),uri.getUserInfo(),uri.getHost(),uri.getPort(),null,null,null);
        } catch (URISyntaxException e) {
            effetiveURI=null;
        }
        return effetiveURI;
    }
    /**
     * 删除商品
     * @param deleteProductReq
     * @return
     */
    @PostMapping("/product/admin/delete")
    public ResultInfo deleteProduct(@RequestBody  @Valid DeleteProductReq deleteProductReq){
        Product product = new Product();
        BeanUtils.copyProperties(deleteProductReq,product);
        boolean flag = productService.removeProduct(product.getId());
        if (flag){
            return ResultInfo.success();
        }
        return ResultInfo.error(GaLiExceptionEnum.DELETE_ERROR);
    }

    /**
     * 更新商品
     * @param updateProductReq
     * @return
     */
    @PostMapping("/product/admin/update")
    public ResultInfo updateProduct(@RequestBody @Valid UpdateProductReq updateProductReq){
        Product product = new Product();
        BeanUtils.copyProperties(updateProductReq,product);
        boolean flag = productService.reviseProduct(product);
        if (flag){
            return ResultInfo.success();
        }
        return ResultInfo.error(GaLiExceptionEnum.UPDATE_ERROR);
    }

    /**
     * 查询全部商品(分页)
     * @return
     */
    @GetMapping("/product/admin/findAllPages")
    public ResultInfo findAll(@RequestParam("pageNumber") Integer pageNumber,@RequestParam("pageSize") Integer pageSize){
        PageInfo all = productService.findAll(pageNumber, pageSize);
        return ResultInfo.success(all);
    }

    /**
     * 通过id查询商品
     * @param selectProductReq
     * @return
     */
    @PostMapping("/product/admin/findById")
    public ResultInfo findById(@RequestBody  @Valid SelectProductReq selectProductReq){
        Product product = new Product();
        BeanUtils.copyProperties(selectProductReq,product);
        Product byId = productService.findById(product.getId());
        if (byId!=null){
            return ResultInfo.success(byId);
        }
        return ResultInfo.error(GaLiExceptionEnum.SELECT_ERROR);
    }

    /**
     * 名字模糊查询
     * @param selectProductReq
     * @return
     */
    @PostMapping("/product/findFromName")
    public ResultInfo findFromName(@RequestBody  @Valid SelectProductReq selectProductReq){
        Product product = new Product();
        BeanUtils.copyProperties(selectProductReq,product);
        List<Product> fromName = productService.findFromName("%" + product.getName() + "%");
        if (fromName.size()>0){
            return ResultInfo.success(fromName);
        }
        return ResultInfo.error(GaLiExceptionEnum.SELECT_ERROR);
    }

    /**
     * 批量更新
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/product/admin/updates")
    public ResultInfo updates(@RequestParam("ids") Integer[] ids, @RequestParam("status") Integer status){
        boolean flag = productService.updates(ids, status);
        if (flag){
            return ResultInfo.success();
        }
        return ResultInfo.error(GaLiExceptionEnum.UPDATE_ERROR);
    }

    /**
     * 商品列表（前端）
     * @param productListReq
     * @return
     */
    @GetMapping("/product/list")
    public ResultInfo list(@RequestBody @Valid ProductListReq productListReq) {
        PageInfo list = productService.list(productListReq);
        return ResultInfo.success(list);
    }
}
